#!/bin/bash
# ========================================================
# PolarDB-X 8.4.19 一键安装脚本（RPM 离线安装）
# 支持：自动卸载、清理、安装、配置、启动、安全加固
# 注意：适用于 X-Cluster 版本（t-polardbx-engine）
# ========================================================

set -euo pipefail

# ============ 配置参数 ============
RPM_FILE="t-polardbx-engine-8.4.19-20241112.el7.x86_64.rpm"
PACKAGE_NAME="t-polardbx-engine"
USER="polarx"
GROUP="polarx"
INSTALL_DIR="/opt/polardbx_engine"
DATA_DIR="/home/polarx/polardbx-engine"
SERVICE_NAME="polardbx"
MYSQL_PORT="3306"
GEARMAN_PORT="14887"
ROOT_PASSWORD="blessme"
CLUSTER_ID="my_polardbx_cluster"
SERVER_ID="1"
# =================================

echo "开始安装 PolarDB-X ..."

# 1. 检查是否为 root
if [[ $EUID -ne 0 ]]; then
    echo "❌ 请以 root 用户运行此脚本！"
    exit 1
fi

# 2. 停止并清理旧实例
echo "检查是否已经安装，如果已经安装先进行卸载..."
systemctl stop "$SERVICE_NAME" &>/dev/null || true
pkill -f mysqld &>/dev/null || true
sleep 2
yum remove -y "$PACKAGE_NAME" &>/dev/null || true
rm -rf "$INSTALL_DIR" "$DATA_DIR"
userdel "$USER" &>/dev/null || true
groupdel "$GROUP" &>/dev/null || true
groupadd "$GROUP" &>/dev/null || true
useradd -r -s /sbin/nologin -M -g "$GROUP" "$USER" || true
rm -f "/etc/systemd/system/$SERVICE_NAME.service"
systemctl daemon-reload

# 3. 检查 RPM 文件
if [ ! -f "/opt/$RPM_FILE" ]; then
    echo "❌ RPM 文件未找到！请将 '$RPM_FILE' 上传到 /opt/ 目录。"
    exit 1
fi

# 4. 安装 RPM
echo "安装 RPM 包..."
yum install -y "/opt/$RPM_FILE" || {
    echo "❌ RPM 安装失败！"
    exit 1
}
echo "RPM 安装成功。"

# 5. 创建数据目录
echo "创建数据目录..."
mkdir -p "$DATA_DIR"{/data,/log,/run,/tmp}
chown -R "$USER:$GROUP" "$DATA_DIR"

# 6. 生成 polarx_server_uuid
POLAR_UUID=$(uuidgen)
if [ -z "$POLAR_UUID" ]; then
    echo "❌ uuidgen 未安装！请运行：yum install -y util-linux"
    exit 1
fi

# 7. 创建 my.cnf
echo "创建配置文件 my.cnf ..."
# 动态生成 server_id（基于时间+随机）
SERVER_ID=$(date +%s | cut -c8-10)$(printf "%03d" $((RANDOM % 1000)))

cat > "$DATA_DIR/my.cnf" << EOF
[mysqld]
# 基本路径
basedir = $INSTALL_DIR
log_error_verbosity = 2
default_authentication_plugin = mysql_native_password
gtid_mode = ON
enforce_gtid_consistency = ON
log_bin = mysql-binlog
binlog_format = row
binlog_row_image = FULL
master_info_repository = TABLE
relay_log_info_repository = TABLE

# change me if needed
datadir = $DATA_DIR/data
tmpdir = $DATA_DIR/tmp
socket = /tmp/mysql.sock
log_error = $DATA_DIR/log/alert.log
port = $MYSQL_PORT
cluster_id = 1234
cluster_info = 127.0.0.1:14886@1
server_id = $SERVER_ID
EOF
chown "$USER:$GROUP" "$DATA_DIR/my.cnf"
chmod 644 "$DATA_DIR/my.cnf"

# 8. 初始化数据库
echo "初始化数据库..."
sudo -u "$USER" $INSTALL_DIR/bin/mysqld --defaults-file="$DATA_DIR/my.cnf" --initialize-insecure || {
    echo "❌ 初始化失败！请检查目录权限和 my.cnf 内容：$DATA_DIR/my.cnf"
    echo "查看日志：cat $DATA_DIR/log/alert.log"
    exit 1
}
echo "初始化完成。"

# 9. 创建 systemd 服务
echo "创建 systemd 服务..."
cat > "/etc/systemd/system/$SERVICE_NAME.service" << EOF
[Unit]
Description=PolarDB-X Database Server (X-Cluster)
After=network.target

[Service]
Type=simple
User=$USER
Group=$GROUP
ExecStart=$INSTALL_DIR/bin/mysqld --defaults-file=$DATA_DIR/my.cnf
ExecStop=$INSTALL_DIR/bin/mysqladmin -u root -p$ROOT_PASSWORD shutdown
Restart=always
RestartSec=3
TimeoutStartSec=300
LimitNOFILE=65536
LimitNPROC=16384
PIDFile=$DATA_DIR/run/mysql.pid
# 标准输出重定向到 journal
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
echo "服务文件已创建。"

# 10. 启动服务
echo "启动 PolarDB-X 服务..."
systemctl start "$SERVICE_NAME"
sleep 3

# 等待启动
echo "等待数据库启动..."
timeout 60 bash -c "until mysql -u root -h 127.0.0.1 -P $MYSQL_PORT -e 'exit' 2>/dev/null; do sleep 2; done" || {
    echo "❌ 启动失败！请检查日志：journalctl -u $SERVICE_NAME -n 100"
    journalctl -u "$SERVICE_NAME" -n 30 --no-pager
    exit 1
}
echo "服务已启动！"

# 11. 设置 root 密码并允许远程登录
echo "设置 root 密码并允许远程登录..."

# 第一步：使用空密码登录，为 root@localhost 设置密码
$INSTALL_DIR/bin/mysql -u root -h 127.0.0.1 -P $MYSQL_PORT -e "
ALTER USER 'root'@'localhost' IDENTIFIED BY '$ROOT_PASSWORD';
" || {
    echo "❌ 设置 root@localhost 密码失败！"
    exit 1
}

# 第二步：创建 root@% 并授权
mysql -u root -h 127.0.0.1 -P $MYSQL_PORT -p$ROOT_PASSWORD -e "
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY '$ROOT_PASSWORD';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
" || {
    echo "❌ 创建 root@% 用户失败！"
    exit 1
}
echo "root@% 用户已创建并授权，支持远程登录。"


# 12. 开机自启
systemctl enable "$SERVICE_NAME"
echo "✅ 开机自启已启用。"

echo "检查并开放防火墙端口 $MYSQL_PORT ..."

# 13. 开放防火墙mysql端口
if systemctl is-active firewalld &>/dev/null; then
    echo "开放防火墙端口 $MYSQL_PORT ..."
    firewall-cmd --permanent --add-port="$MYSQL_PORT"/tcp
    firewall-cmd --reload
    echo "防火墙已开放端口 $MYSQL_PORT"
else
    echo "firewalld 未运行，跳过防火墙配置。"
fi

# 14. 输出连接信息
echo " ==================================================="
echo "✅ PolarDB-X 安装成功！"
echo "连接信息："
echo "   主机: $(hostname -I | awk '{print $1}' || echo '127.0.0.1')"
echo "   端口: $MYSQL_PORT"
echo "   用户: root"
echo "   密码: $ROOT_PASSWORD"
echo "   启动: systemctl start $SERVICE_NAME"
echo "   停止: systemctl stop $SERVICE_NAME"
echo "   日志: journalctl -u $SERVICE_NAME -f"
echo "   配置: $DATA_DIR/my.cnf"
echo "==================================================="
